<?php

namespace addons\groupon\model\store;

use think\Model;
use traits\model\SoftDelete;
use addons\groupon\model\Store;
use addons\groupon\model\User;
use addons\groupon\model\OrderItem;
use addons\groupon\exception\Exception;

class UpkeepLog extends Model
{


    // 表名
    protected $name = 'groupon_store_upkeep_log';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = false;

    // 发货状态
    const DISPATCH_STATUS_NOSEND = 1;       // 待服务
    const DISPATCH_STATUS_SENDED = 2;        // 服务中
    const DISPATCH_STATUS_GETED = 3;        // 待审核
    const DISPATCH_STATUS_SUCEE = 4;        // 已完成
    const DISPATCH_STATUS_NO    = 5;        // 已完成
    // 追加属性
    protected $append = [
        'dispatch_status_name',
        'create_time_text'
    ];

    public static function getList($params) {
        extract($params);

        $user = User::info();
        $store = Store::info();

        $express = self::with('itemFirst')->where('store_id', $store['id'])->order('id', 'desc')->paginate($per_page ?? 10);        // 未填写物流信息的包裹也会出现在包裹列表

        return $express;
    }


    public static function getDetail($params) {
        extract($params);

        $user = User::info();
        $store = Store::info();

        $express = self::with(['log', 'items'])->where('store_id', $store['id'])->where('id', $id)->find();     // 未填写物流信息的包裹也可以查看
        if (!$express) {
            new Exception('未找到包裹');
        }
        $express = $express->toArray();
        $items = $express['items'];

        $newItems = [];
        foreach ($items as $item) {
            $goodsKey = $item['goods_id'] . '-' . $item['goods_sku_price_id'];
            if (isset($newItems[$goodsKey])) {
                $newItems[$goodsKey]['goods_num'] = $newItems[$goodsKey]['goods_num'] + $item['goods_num'];
            } else {
                $newItems[$goodsKey] = $item;
            }
        }

        $express['items'] = array_values($newItems);

        return $express;
    }

    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    /**
     * @Author:zhu
     * @return void
     */
    public static function startService($params){
        $store = Store::info();
        // 包裹里面的商品全部到货
        try {
            \think\Db::transaction(function () use ($store, $params) {
                $express = self::where('store_id', $store['id'])->where('status','=',1)->where('id', $params['id'])->lock(true)->find();
                if (!$express) {
                    new Exception('未找到服务');
                }
                // 将包裹确认收货
                $express->status = self::DISPATCH_STATUS_SENDED;
                $express->start_time = time();
                $express->save();
            });
        }catch (\Exception $exception){
            new Exception($exception->getMessage());
        }

    }
    /**
     * 订单到货
     */
    public static function operArrive($params)
    {
        $user = User::info();
        $store = Store::info();
        

        // 包裹里面的商品全部到货
        \think\Db::transaction(function () use ($user, $store, $params) {
            extract($params);

            $express = self::where('store_id', $store['id'])->where('express_no', 'not null')->where('id', $id)->lock(true)->find();

            if (!$express) {
                new Exception('未找到包裹');
            }

            // 包裹中订单
            $orders = Order::payed()->where('store_id', $store['id'])->with(['item' => function ($query) use ($express) {
                return $query->where('store_express_id', $express['id'])
                    ->where('dispatch_status', \addons\groupon\model\OrderItem::DISPATCH_STATUS_READY)
                    ->where('refund_status', 'not in', [OrderItem::REFUND_STATUS_OK, OrderItem::REFUND_STATUS_FINISH]);
            }])->whereExists(function ($query) use ($express) {
                $itemTableName = (new OrderItem())->getQuery()->getTable();
                $tableName = (new Order())->getQuery()->getTable();

                return $query->table($itemTableName)
                    ->where($itemTableName . '.order_id=' . $tableName . '.id')
                    ->where('store_express_id', $express['id'])
                    ->where('dispatch_status', \addons\groupon\model\OrderItem::DISPATCH_STATUS_READY)
                    ->where('refund_status', 'not in', [OrderItem::REFUND_STATUS_OK, OrderItem::REFUND_STATUS_FINISH]);
            })->select();

            // 将包裹确认收货
            $express->dispatch_status = self::DISPATCH_STATUS_GETED;
            $express->save();

            // 将订单标记为已到货
            (new Order)->storeArrive($express, $orders);
        });
    }

    public function getDispatchStatusList()
    {
        return ['0' => '未发货', '1' => '已发货', '2' => '已收货'];
    }

    public function getDispatchStatusNameAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['dispatch_status']) ? $data['dispatch_status'] : '');
        $list = $this->getDispatchStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }



    public function itemFirst() {
        return $this->belongsTo(OrderItem::class, 'order_item_id', 'id');
    }

//
//    public function items() {
//        return $this->hasMany(OrderItem::class, 'store_express_id');
//    }


}
